package cn.bigcontainer.alt.sys.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.sys.dto.UserDto;
import cn.bigcontainer.alt.sys.exception.SysException;
import cn.bigcontainer.alt.sys.mapper.UserMapper;
import cn.bigcontainer.alt.sys.mapper.UserRoleMapper;
import cn.bigcontainer.alt.sys.po.User;
import cn.bigcontainer.alt.sys.po.UserRole;
import cn.bigcontainer.alt.sys.service.SysUserService;

/**
 * @author jiaod
 * @date 2021年3月30日
 */
@Service
@Transactional
@Slf4j
public class SysUserServiceImpl implements SysUserService {

	@Resource
	private UserMapper userMapper;
	
	@Resource
	private UserRoleMapper userRoleMapper;
	
	@Override
	public Integer createUser(String loginName, String password, String xm, Integer... roleIds) {
		UserDto user = new UserDto();
		user.setLoginName(loginName);
		user.setPassword(password);
		user.setName(xm);
		return createUser(user, roleIds);
	}

	@Override
	public Integer createUser(UserDto userDto, Integer... roleIds) {
		if (WoKit.isEmpty(userDto.getLoginName())) {
			throw new SysException(SysException.ERROR_NULL, "登录名");
		}
		if (WoKit.isEmpty(userDto.getPassword())) {
			String password = userDto.getLoginName();
			if (password.length() > 6) {
				password = password.substring(password.length() - 6);
			}
			userDto.setPassword(password);
		}
		if (WoKit.isEmpty(userDto.getName())) {
			throw new SysException(SysException.ERROR_NULL, "姓名");
		}
		// 创建用户
		User user = WoKit.cloneBySetter(userDto, User.class);
		Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("login_name", user.getLoginName()));
		if (count > 0) {
			throw new SysException(SysException.ERROR_DUPLICATE, "登录名", user.getLoginName());
		}
		user.setCreateTime(new Date());
		userMapper.insert(user);
		user.setPassword(WoKit.getMD5(user.getId(), user.getPassword()));
		userMapper.updateById(user);
		// 关联用户和角色
		if (roleIds != null) {
			for (Integer roleId : roleIds) {
				if (roleId == null) {
					continue;
				}
				UserRole userRole = new UserRole();
				userRole.setRoleId(roleId);
				userRole.setUserId(user.getId());
				userRoleMapper.insert(userRole);
			}
		}
		return user.getId();
	}

	@Override
	public UserDto getUser(Integer userId) {
		User user = userMapper.selectById(userId);
		if (user == null) {
			return null;
		}
		return new UserDto(user);
	}

	@Override
	public void addRoles(Integer userId, Integer... roleIds) {
		List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", userId));
		List<Integer> roleIdList = WoKit.asList(roleIds);
		for (UserRole userRole : userRoles) {
			Iterator<Integer> iterator = roleIdList.iterator();
			while (iterator.hasNext()) {
				if (iterator.next().equals(userRole.getRoleId())) {
					iterator.remove();
				}
			}
		}
		for (Integer roleId : roleIdList) {
			if (roleId == null) {
				continue;
			}
			UserRole userRole = new UserRole();
			userRole.setRoleId(roleId);
			userRole.setUserId(userId);
			userRoleMapper.insert(userRole);
		}
	}

	@Override
	public void removeUser(Integer userId) {
		userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
		userMapper.deleteById(userId);
	}


	public void resetPasswordByLoginName(String loginName) {
		User user = userMapper.selectOne(new QueryWrapper<User>() {{
			eq("login_name", loginName);
		}});
		reset(user);
	}

	public void resetPasswordByUserId(String userId) {
		User user = userMapper.selectById(userId);
		reset(user);
	}

	private void reset(User user) {
		// 认证
		if (user == null) {
			throw new SysException(SysException.ERR_LOGIN);
		}
		String newPassword = user.getLoginName();
		if (newPassword.length() > 6) {
			newPassword = newPassword.substring(newPassword.length() - 6);
		}
		user.setPassword(WoKit.getMD5(user.getId(), newPassword));
		userMapper.updateById(user);
	}
}
